package fr.dauphine.bookstore.frontoffice;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import fr.dauphine.bookstore.commun.MessagesUtil;
import fr.dauphine.bookstore.hibernate.HibernateUtil;
import fr.dauphine.bookstore.modele.User;

/**
 * Login de l'utilisateur.
 */
public final class LoginServlet extends HttpServlet {

	/**
	 * Serial version UID.
	 */
	private static final long serialVersionUID = 1676479421840487600L;

	/**
	 * Traite la methode POST.
	 * 
	 * @param request
	 *            Requete
	 * @param response
	 *            Reponse
	 * @throws ServletException
	 *             Erreur de servlet
	 * @throws IOException
	 *             Erreur d'entree/sortie
	 */
	protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		String login = request.getParameter("login");
		String password = request.getParameter("pass");

		// Hash du mot de passe
		password = DigestUtils.md5Hex(password);
		
		Session hSession = HibernateUtil.getSessionFactory().getCurrentSession();
		Criteria crit = hSession.createCriteria(User.class);
		crit.add(Restrictions.eq("userName", login));
		crit.add(Restrictions.eq("password", password));

		User user = (User) crit.uniqueResult();

		if (user == null) {
			MessagesUtil.addMessage(request, MessagesUtil.ERROR, "Login ou mot de passe incorrect");
			request.getRequestDispatcher("index.jsp").forward(request, response);

		} else {
			SessionUtil.setUser(request.getSession(), user);
			response.sendRedirect("index.jsp");
		}
	}
}
